<?php
namespace app\admin\controller;

class Article extends Common
{
    private $obj;
    public function _initialize()
    {
        parent::_initialize();
        $this->obj = model('Article');
    }

    public function index()
    {
        $category_id = input('param.category_id', 0);
        $where = [];
        if ($category_id > 0) {
            $where['category_id'] = $category_id;
        }
        if (input('?param.title')) {
            $where['title'] = ['like', '%'. input('param.title') .'%'];
        }
        $data = $this->obj->getList($where);

        $cate = model('category')->getCateTreeByPid();
        $this->assign('cate', $cate);

        $this->assign('data', $data);

        return view();
    }

    public function save_article() {
        $id = input('param.id', 0);
        $cid = input('param.category_id', 0);
        if (request()->isPost()) {
            /**
             * 组装数据
             */
            $data['title'] = input('post.title', '');
            $data['author'] = input('post.author', '');
            $data['category_id'] = $cid;
            $data['image'] = input('post.image', '');
            $data['hits'] = input('post.hits', '');
            $data['index'] = input('post.index', '');
            if ($create_time = input('post.create_time')) {
                $data['create_time'] = strtotime($create_time);
            }

            /**
             * 保存数据
             */
            $where = $id > 0 ? ['id' => $id] : [];
            $rs = $this->obj->save($data, $where);

            // 清理缓存
            \app\api\service\Base::clear_cache();

            if ($rs) {
                $id = $id > 0 ? $id : $this->obj->id;
                $desc = input('param.desc', '');
                $content = input('param.content', '');
                $desc_data = [
                    'desc' => $desc,
                    'content' => $content
                ];
                $article_desc = model('ArticleDesc')->get(['article_id' => $id]);
                if ($article_desc) {
                    model('ArticleDesc')->save($desc_data, ['article_id' => $id]);
                } else {
                    $desc_data['article_id'] = $id;
                    model('ArticleDesc')->save($desc_data);
                }

                $this->success('保存成功', '');
            } else {
                $this->error('保存失败');
            }
        } else{
            $data = [];
            if ($id > 0) {
                $data = $this->obj->get(['id' => $id]);
            }
            $this->assign('data', $data);

            $ztree = model('Category')->getCateZTree();
            $this->assign('ztree', $ztree);

            return view();
        }
    }
}
